﻿using MQTTServer.Bll;
using MQTTServer.Model;
using MQTTServer.Model.UDPEvents;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MQTTServer.UDP
{
    public partial class UPDServer : Form
    {
        private delegate void AddItemToListBoxDelegate(string str);
        private delegate void AddItemToListBoxDelegate2(string str);
        /// <summary>
        /// 客户端列表显示
        /// </summary>
        /// <param name="str"></param>
        private delegate void AddItemToListBoxDelegate3(ClientPayloadDataModel client);
        /// <summary>
        /// 删除掉线的客户端列表显示
        /// </summary>
        /// <param name="str"></param>
        private delegate void DeleteCloseClientDelegate(ClientPayloadDataModel client);

        /// <summary>
        /// 所有聊天消息显示
        /// </summary>
        /// <param name="str"></param>
        private delegate void messageBoxDelegate(string str);
        UPDServerBll UPDServerBll;
        public UPDServer()
        {
            InitializeComponent();
            button2.Enabled = false;

            Task.Run(() =>
            {
                while (true)
                {
                    if(UPDServerBll != null)
                    { 
                    UPDServerBll.ClientClose();
                    Thread.Sleep(60000);
                    }
                }
            });
        }

        private void button3_Click(object sender, EventArgs e)
        {
            UPDServerBll = new UPDServerBll();
            UPDServerBll.ServerIp = textBox1.Text.Trim();
            UPDServerBll.ServerPort = int.Parse(textBox2.Text.Trim());
            UPDServerBll.ServerConnectdEvent += this.ServerConnectd;
            UPDServerBll.ExceptionEvent += this.ExceptionEventd;
            UPDServerBll.SendDatadEvent += this.SendDataEvent;
            UPDServerBll.ReceivedDataEvent += this.ReceivedDataEvent;
            UPDServerBll.NewClientConnectdEvent += this.NewClientConnectdEvent;
            UPDServerBll.CloseClientConnectdEvent += this.CloseClientConnectdEvent;
            //UPDServerBll.Server_ClientListModel.ClientList.Clear();
            UPDServerBll.ServerStart();
            button3.Enabled = false;
            button2.Enabled = true;
        }
        public void ServerConnectd(object sender, ServerConnectdEventArgs e)
        {
            AddItemToListBox(e.Message);
        }
        /// <summary>
        /// 发送数据完成事件 将发送的数据添加到聊天区域和日志区域
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void SendDataEvent(object sender, ClientDataEventArgs e)
        {
            ClientPayloadDataModel cdata = new ClientPayloadDataModel();
            cdata = JsonConvert.DeserializeObject<ClientPayloadDataModel>(e.StrJson);
            if (cdata.DataMessage.Length > 0)
            {
                string str = cdata.IsSiLiao ? "[私聊]" : "[公聊]";
                string mesg = str + cdata.SendDataClientName + "对" + cdata.ClientName + "说:" + cdata.DataMessage + "--" + cdata.DataMessageTime;
                AddmessageBox(mesg);
            }
            AddItemToListBox("数据接收:" + e.StrJson);
        }
        /// <summary>
        /// 服务器接收数据事件 根据接收人信息进行消息分发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ReceivedDataEvent(object sender, ClientDataEventArgs e)
        {
            ClientPayloadDataModel cdata = new ClientPayloadDataModel();
            cdata = JsonConvert.DeserializeObject<ClientPayloadDataModel>(e.StrJson);
            if (cdata.DataMessage.Length > 0)
            {
                if (cdata.IsSiLiao)
                {
                    UPDServerBll.BeginSendData(e.StrJson, cdata.ClientName);
                    UPDServerBll.BeginSendData(e.StrJson, cdata.SendDataClientName);
                }
                else
                {
                    UPDServerBll.SendAllClient(e.StrJson);
                }
            }
        }
        /// <summary>
        /// 新的客户登陆事件 将新客户加入客户列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void NewClientConnectdEvent(object sender, ClientMessageDataEventArgs e)
        {
            //if (listBox1.Items.IndexOf(e.ClientOBJ.SendDataClientName) == -1)
            //    AddItemToListBox3(e.ClientOBJ.SendDataClientName);
            //int count = listBox1.Items.IndexOf(e.ClientOBJ.SendDataClientName + "--" + e.ClientOBJ.ClinetIpProt);
            //if (count == -1)
            //{
            //    AddItemToListBox3(e.ClientOBJ.SendDataClientName + "--" + e.ClientOBJ.ClinetIpProt);
            //}
            //else
            //{
            //    listBox1.Items.RemoveAt(count);
            //    AddItemToListBox3(e.ClientOBJ.SendDataClientName + "--" + e.ClientOBJ.ClinetIpProt);
            //}

            AddItemToListBox3(e.ClientOBJ);

        }
        public void CloseClientConnectdEvent(object sender, ClientMessageDataEventArgs e)
        {
            DeleteCloseClient(e.ClientOBJ);
        }

        public void ExceptionEventd(object sender, ExceptionEventArgs e)
        {
            AddItemToListBox(e.ExceptionMessage);
        }
        private void AddItemToListBox(string str)
        {
            if (richTextBox1.InvokeRequired)
            {
                AddItemToListBoxDelegate d = AddItemToListBox;
                richTextBox1.Invoke(d, str);
            }
            else
            {
                string str2 = richTextBox1.Text.Insert(0, str + "  " + DateTime.Now.ToString() + "\r\n");
                richTextBox1.Text = str2;
            }
        }
        private void AddmessageBox(string str)
        {
            if (messageBox.InvokeRequired)
            {
                messageBoxDelegate d = AddmessageBox;
                messageBox.Invoke(d, str);
            }
            else
            {
                messageBox.AppendText(str + "\r\n");
                messageBox.ScrollToCaret();
            }
        }
        /// <summary>
        /// 客户列表显示
        /// </summary>
        /// <param name="str"></param>
        private void AddItemToListBox3(ClientPayloadDataModel client)
        {
            if (listBox1.InvokeRequired)
            {
                AddItemToListBoxDelegate3 d = AddItemToListBox3;
                listBox1.Invoke(d, client);
            }
            else
            {

                int count = -1;
                for (int i = 0; i < listBox1.Items.Count; i++)
                {
                    if (listBox1.Items[i].ToString().Contains(client.SendDataClientName + "--"))
                    {
                        //count = i;
                        //break;
                        listBox1.Items.RemoveAt(i);
                    }
                }
                if (count == -1)
                {
                    listBox1.Items.Insert(0, client.SendDataClientName + "--" + client.ClinetIpProt);
                }
                //else
                //{
                //    listBox1.Items.RemoveAt(count);
                //    listBox1.Items.Insert(0, client.SendDataClientName + "--" + client.ClinetIpProt);
                //}
                listBox1.Refresh();
            }
        }
        /// <summary>
        /// 删除掉线客户列表显示
        /// </summary>
        /// <param name="str"></param>
        private void DeleteCloseClient(ClientPayloadDataModel client)
        {
            if (listBox1.InvokeRequired)
            {
                DeleteCloseClientDelegate d = DeleteCloseClient;
                listBox1.Invoke(d, client);
            }
            else
            {
                for (int k = 0; k < client.ClientList.Count; k++)//掉线的客户端集合
                {
                    for (int i = 0; i < listBox1.Items.Count; i++)//客户列表中的客户
                    {
                        if (listBox1.Items[i].ToString().Contains(client.ClientList[k].SendDataClientName + "--"))
                        {
                            //count = i;
                            //break;
                            listBox1.Items.RemoveAt(i);
                        }
                    }
                }
                listBox1.Refresh();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            UPDServerBll.ServerIp = null;
            UPDServerBll.ServerConnectdEvent -= this.ServerConnectd;
            UPDServerBll.ExceptionEvent -= this.ExceptionEventd;
            UPDServerBll.SendDatadEvent -= this.SendDataEvent;
            UPDServerBll.ReceivedDataEvent -= this.ReceivedDataEvent;
            UPDServerBll.NewClientConnectdEvent -= this.NewClientConnectdEvent;
            UPDServerBll.Server_ClientListModel.ClientList.Clear();
            UPDServerBll.ServerClose();
            button3.Enabled = true;
            button2.Enabled = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox8.Text.Trim().Length == 0)
            {
                MessageBox.Show("请填写发送信息！");
                return;
            }

            if (checkBox2.Checked)
            {
                UPDServerBll.SendAllClientJsonTextFromText(textBox8.Text.Trim(), checkBox1.Checked);
            }
            else
            {
                if (textBox7.Text.Trim().Length == 0)
                {
                    MessageBox.Show("请提供接收人姓名");
                    return;
                }
                else
                {
                    if (checkBox1.Checked)
                    {
                        //通过服务器，直接给单独的客户发送数据
                        string mesgData = UPDServerBll.GetOneCientJSONDataToText(textBox7.Text.Trim(), textBox8.Text.Trim(), true);
                        string username = textBox7.Text.Trim();
                        UPDServerBll.BeginSendData(mesgData, username);
                    }
                    else
                    {
                        UPDServerBll.SendAllClientJsonTextFromText(textBox8.Text.Trim(), false);
                    }
                }
            }

        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox2.Checked)
            {
                //label7.Visible = false;
                textBox7.Visible = false;
                checkBox1.Visible = false;
            }
            else
            {
                //label7.Visible = true;
                textBox7.Visible = true;
                checkBox1.Visible = true;
            }
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox1.SelectedItem != null)
            {
                // textBox7.Text = listBox1.SelectedItem.ToString();
                int len = listBox1.SelectedItem.ToString().IndexOf("--");
                textBox7.Text = listBox1.SelectedItem.ToString().Substring(0, len);
            }
        }
    }
}
